//
//  MainViewController.m
//  CameraDemo
//
//  Created by Gamefire on 16/3/23.
//  Copyright © 2016年 Gamefire. All rights reserved.

#import "TakingpicturesViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

#import "Header.h"



#define kMainScreenWidth [UIScreen mainScreen].bounds.size.width
#define kMainScreenHeight  [UIScreen mainScreen].bounds.size.height
@interface TakingpicturesViewController (){
    
    
    UIImageView *flashImageView;
    UIImage *image;
    UIImageView *switchImageView;
    
}
//界面控件
@property (nonatomic,strong)UIView *backView;
@property (nonatomic,strong)UIView *topView;
@property (nonatomic,strong)UISegmentedControl *switchCarmeraSegment;
@property (nonatomic,strong)UIButton *btn;
@property (nonatomic,strong)UIButton *flashbtn;
@property (nonatomic,strong)UIButton *switchbtn;
@property (nonatomic,strong)UIButton *topClearBtn;
@property (nonatomic,strong)UIButton *topUseBtn;
@property (nonatomic,strong)UIImage *image;
@property (nonatomic,strong)UIImageView *imageView;
//执行输入输出之间的数据传递
@property (nonatomic,strong)AVCaptureSession *session;
// 输入设备
@property (nonatomic,strong)AVCaptureDeviceInput *videoInput;
// 照片输出流
@property (nonatomic,strong)AVCaptureStillImageOutput *stillImageOutput;
// 预览图片
@property (nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;
// 记录开始的缩放比例
@property (nonatomic,assign)CGFloat beginGestureScale;
//最后的缩放比例
@property (nonatomic,assign)CGFloat effectiveScale;

@end

@implementation TakingpicturesViewController{
    
    BOOL isUsingFrontFacingCamera;
    
}



- (void)viewDidAppear:(BOOL)animated{
    [super viewDidDisappear:YES];
    if (self.session) {
        [self.session startRunning];
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    if (self.session) {
        [self.session stopRunning];
    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



- (void)viewDidLoad {
    [super viewDidLoad];
    isUsingFrontFacingCamera = NO;
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kMainScreenWidth , kMainScreenHeight - 274.0 / 2.0)];
    [self.view addSubview:_backView];
    
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _backView.bounds.size.width, _backView.bounds.size.height)];
    [_topView setBackgroundColor:[UIColor clearColor]];
    [_backView addSubview:_topView];
    
    //初始化预览图层
    image = nil;
    image = [UIImage imageNamed:@"Button.png"];
    [self initAVCaptureSession];
    
    _switchCarmeraSegment = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, kMainScreenHeight - 274.0/2.0 - 44, kMainScreenWidth, 274.0/2.0 )];
    [_switchCarmeraSegment setBackgroundColor:[UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1]];
    [self.view addSubview:_switchCarmeraSegment];
    
    //shooting button
    _btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width /2.0 - image.size.width /2.0, 28, image.size.width, image.size.height)];
    [_btn setBackgroundImage:image forState:UIControlStateNormal];
    _btn.layer.cornerRadius = 22.5;
    
    [_btn addTarget:self action:@selector(shootingEvent) forControlEvents:UIControlEventTouchDown];
    [_switchCarmeraSegment addSubview:_btn];
    //flash button
    image = [UIImage imageNamed:@"lightning.png"];
    
    flashImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 18.0 / 2.0, image.size.width, image.size.height)];
    [flashImageView setImage:image];
    [_switchCarmeraSegment addSubview:flashImageView];
    
    _flashbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_flashbtn setFrame:CGRectMake(10.0, 18.0/2.0, 50, 50)];
    [_flashbtn addTarget:self action:@selector(flsashEvent) forControlEvents:UIControlEventTouchUpInside];
    [_switchCarmeraSegment addSubview:_flashbtn];
    //Switch the lens
    image = [UIImage imageNamed:@"camera.png"];
    
    switchImageView = [[UIImageView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - image.size.width - 10.0, 18.0 / 2.0, image.size.width, image.size.height)];
    [switchImageView setImage:image];
    [_switchCarmeraSegment addSubview:switchImageView];
    _switchbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_switchbtn setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - image.size.width - 30.0, 18.0/2.0, 50, 50)];
    [_switchbtn addTarget:self action:@selector(SwitchEvent) forControlEvents:UIControlEventTouchUpInside];
    [_switchCarmeraSegment addSubview:_switchbtn];
    
    image = [UIImage imageNamed:@"close"];
    
    _topClearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_topClearBtn setFrame:CGRectMake(10.0, 15.0 / 2.0, image.size.width, image.size.height)];
    [_topClearBtn setHidden:YES];
    [_topClearBtn setBackgroundImage:image forState:UIControlStateNormal];
    [_topClearBtn addTarget:self action:@selector(ClearEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_topClearBtn];
    
    _topUseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_topUseBtn setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 128.0 / 2.0 - 20.0 / 2.0, 15.0 / 2.0, 128.0 / 2.0, 50.0 / 2.0)];
    [_topUseBtn setBackgroundColor:[UIColor colorWithRed:255.0 / 255.0 green:204.0 / 255.0 blue:0.0 / 255.0  alpha:1]];
    [_topUseBtn setTitle:@"使用" forState:UIControlStateNormal];
    [_topUseBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0]];
    [_topUseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_topUseBtn addTarget:self action:@selector(UseEvent) forControlEvents:UIControlEventTouchUpInside];
    _topUseBtn.layer.cornerRadius = 50.0 / 2.0 / 2.0;
    [_topUseBtn setHidden:YES];
    [self.view addSubview:_topUseBtn];
}


- (void)shootingEvent{
    
    UIButton *button = _btn;
    
    if (_btn.selected == YES) {
        [_btn setTitle:@"" forState:UIControlStateNormal];
        [_topClearBtn setHidden:YES];
        [_topUseBtn setHidden:YES];
        [_topView removeFromSuperview];
        [_imageView removeFromSuperview];
        [switchImageView setHidden:NO];
        [flashImageView setHidden:NO];
        [_switchbtn setHidden:NO];
        [_flashbtn setHidden:NO];
    }else{
        [_btn setTitle:@"重拍" forState:UIControlStateNormal];
        [_btn setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
        [_topClearBtn setHidden:NO];
        [_topUseBtn setHidden:NO];
        [self touchEvent];
        [_backView addSubview:_topView];
        [_imageView setImage:_image];
        [flashImageView setHidden:YES];
        [switchImageView setHidden:YES];
        [_switchbtn setHidden:YES];
        [_flashbtn setHidden:YES];
        
    }
    _btn.selected = !button.selected;
}

- (void)touchEvent{
    
    AVCaptureConnection *stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
    AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation];
    [stillImageConnection setVideoOrientation:avcaptureOrientation];
    
    [stillImageConnection setVideoScaleAndCropFactor:self.effectiveScale];
    
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        _image =[UIImage imageWithData:jpegData];
        //        NSLog(@"%d", [jpegData length]);
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        [_imageView setImage:_image];
        [_topView addSubview:_imageView];
        
        //        CFDictionaryRef attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault,
        //                                                                    imageDataSampleBuffer,
        //                                                                    kCMAttachmentMode_ShouldPropagate);
        
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            return ;
        }
        //        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        //        [library writeImageDataToSavedPhotosAlbum:jpegData metadata:(__bridge id)attachments completionBlock:^(NSURL *assetURL, NSError *error) {
        
        UIImageWriteToSavedPhotosAlbum(_image, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), NULL);
        
        
        //        }];
        
    }];
    
    //    [[NSNotificationCenter defaultCenter] postNotificationName:imageSaveSuccess object:nil];
}

- (void)savedPhotoImage:(UIImage*)image didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo
{
    [[NSNotificationCenter defaultCenter] postNotificationName:imageSaveSuccess object:nil];
}

// switch
- (void)SwitchEvent{
    NSLog(@"Switch");
    CATransition *animation = [CATransition animation];
    animation.duration = .5f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = @"oglFlip";
    
    AVCaptureDevicePosition desiredPostion;
    if (isUsingFrontFacingCamera){
        desiredPostion = AVCaptureDevicePositionBack;
        animation.subtype = kCATransitionFromLeft;
    }else{
        desiredPostion = AVCaptureDevicePositionFront;
        animation.subtype = kCATransitionFromRight;
    }
    [_previewLayer addAnimation:animation forKey:nil];
    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
        if ([d position] == desiredPostion) {
            
            [_previewLayer.session beginConfiguration];
            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
            for (AVCaptureDeviceInput *oldInput in _previewLayer.session.inputs) {
                [[_previewLayer session]removeInput:oldInput ];
            }
            [_previewLayer.session addInput:input];
            [_previewLayer.session commitConfiguration];
            break;
        }
    }
    isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}


//flash
- (void)flsashEvent{
    image = [UIImage imageNamed:@"ShutDownlight"];
    [flashImageView  setImage:image];
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //修改前必须先锁定
    [device lockForConfiguration:nil];
    
    // 必须先判定是否有闪光灯，否则如果没有闪光灯会崩溃
    if ([device hasFlash]) {
        
        if (device.flashMode == AVCaptureFlashModeOff) {
            device.flashMode = AVCaptureFlashModeOn;
        }else if (device.flashMode == AVCaptureFlashModeOn){
            device.flashMode = AVCaptureFlashModeAuto;
        }else if (device.flashMode == AVCaptureFlashModeAuto){
            device.flashMode = AVCaptureFlashModeOff;
            [flashImageView setImage:[UIImage imageNamed:@"lightning.png"]];
        }
        
    }else{
        NSLog(@"Device does not support flash");
    }
    [device unlockForConfiguration];
}


// init
- (void)initAVCaptureSession{
    self.session = [[AVCaptureSession alloc] init];
    
    NSError *error;
    // 更改这个设置的时候必须先锁定设备,修改完后在解锁，否则崩溃
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    
    if (error) {
        NSLog(@"%@",error);
    }
    
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    //输出设置。 输出jpeg格式照片
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    
    //    [self.session beginConfiguration];
    
    if ([self.session canAddInput:_videoInput])
    {
        [self.session addInput:_videoInput];
    }
    
    if ([self.session canAddOutput:_stillImageOutput])
    {
        [self.session addOutput:_stillImageOutput];
    }
    
    //    [self.session commitConfiguration];
    self.effectiveScale = self.beginGestureScale = 1.0f;
    
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    _previewLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    self.backView.layer.masksToBounds = YES;
    [self.backView.layer addSublayer:_previewLayer];
    
}

- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft) {
        result = AVCaptureVideoOrientationLandscapeRight;
    }else if (deviceOrientation == UIDeviceOrientationLandscapeRight){
        result = AVCaptureVideoOrientationLandscapeLeft;
    }
    return result;
}


//取消拍照
- (void)ClearEvent
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//使用照片
- (void)UseEvent
{
    [_MTakingpicturesViewControllerDelegate pushTakePhoto:UIImagePNGRepresentation(_image)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
